<?php

/* 
 * 用户管理
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class UserController extends AppController
{
    public function __construct() {
        parent::__construct();
        $this->modelObj = new AdminUserModel();
        $this->log_type = '用户管理';
        $this->cookie_key = 'reg_cookie';
    }    
    /**
     * 浏览
     */
    public function view(){
        $this->get_data();
        $this->display('user_list');
    }
    public function query(){
        $this->get_data();        
        $this->ret['status'] = 0;
        $this->ret['content'] = $this->fetch('user_list');
        exit(json_encode($this->ret));
    }
    /**
     * 清除缓存
     */
    public function clear() {
        $files = TEMP_PATH . 'x_config.php';
        $bool = unlink($files);
        if($bool) {
            $this->show_msg('清理成功', 'c=index&m=index', false);
        } else {
            $this->show_msg('清理失败', 'c=index&m=index');
        }
    }
    public function del(){
        $user_id = intval($_POST['user_id']);
        if($user_id > 0) {
            $data = array(
                'is_del' => 1,
            );
            $bool = AdminUserModel::load()->update_user_info($user_id, $data);
            if($bool) {
                echo $this->setReturn(0, '删除ok');
            } else {
                echo $this->setReturn(200, '删除失败');
            }
        } else {
            echo $this->setReturn(100, '非法操作');
        }
    }
    public function unlink(){
        $user_id = intval($_POST['user_id']);
        if($user_id > 0) {
            $info = AdminUserModel::load()->get_info($user_id);
            if($info['is_admin'] == 1) {
                echo $this->setReturn(101, '管理员帐号不能删除');exit;
            }
            $where = array(
                'user_id' => $user_id,
            );
            $bool = AdminUserModel::load()->delete($where);
            if($bool) {
                echo $this->setReturn(0, '删除ok');
            } else {
                echo $this->setReturn(200, '删除失败');
            }
        } else {
            echo $this->setReturn(100, '非法操作');
        }
    }

    /**
     * 设置
     */
    public function set(){
        $this->create_token();
        $row = AdminUserModel::load()->get_info($this->user_id);
        $this->assign('user', $row);
        $this->display('user_set');
    }
    public function new_set(){
        $this->check_token();
        if(isset($_POST['user_id']) && $_POST['email'] && $_POST['user_id'] > 0) {
            /*处理邮箱*/
            $email = $_POST['email'];
            $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
            if(!$email || !preg_match($pattern, $email)) {
                $this->show_msg('您输入的邮箱格式不正确');
            }
            
            /*处理是否与当前用户名一致*/
            if($this->user_id == $_POST['user_id']) {
                //允许修改邮箱,用户名
                $user_name = trim($_POST['user_name']);
                $check_email = AdminUserModel::load()->check_email($this->user_id,'',$email);
                if($check_email) {
                    $this->show_msg('您的邮箱已占用');
                }            
                $check_user_name = AdminUserModel::load()->check_user_name($this->user_id, $user_name);
                if($check_user_name) {
                    $this->show_msg('您的用户名被占用');
                }                
                if(($user_name || $email) && empty($_POST['old']) && empty($_POST['new_pass']) && empty($_POST['new_pass_confirm'])) {
                    $data = array();
                    if($user_name) {
                        $data['user_name'] = $user_name;
                    }
                    if($email) {
                        $data['email'] = $email;
                    }
                    $bool = AdminUserModel::load()->update_user_info($this->user_id, $data);
                    if($bool) {
                        $this->show_msg('修改成功');
                    } else {
                        $this->show_msg('邮箱修改失败');
                    }
                }
                $user_info = AdminUserModel::load()->get_info($this->user_id);  
                if($user_info) {
                    $salt = $user_info['salt'];
                    $old_pass = $_POST['old_pass'];                    
                    $secret_pass = pass_encrypt($old_pass, $salt, 'pass_key');
                    if($secret_pass == $user_info['user_pass']) {//验证成功
                        //处理新密码
                        $new_pass = $_POST['new_pass'];
                        $new_pass_confirm = $_POST['new_pass_confirm'];
                        if($new_pass && $new_pass_confirm) {
                            if($new_pass == $new_pass_confirm) {
                                $new_salt = ApiBase::load()->get_unique_id(32, 'salt');
                                $md5_pass = pass_encrypt($new_pass, $new_salt, 'pass_key'); 
                                $data = array(
                                    'user_pass' => $md5_pass,
                                    'salt' => $new_salt,
                                );
                                if($email) {
                                    $data['email'] = $email;
                                }
                                $bool = AdminUserModel::load()->update_user_info($this->user_id, $data);
                                if($bool) {
                                    $this->admin_log('个人设置,用户名:' . $user_info['user_name']);                                    
//                                    $this->show_msg('设置成功', 'index.php?c=login&m=quit');
                                    $this->redirect('manager', 'quit');
                                } else {
                                    $this->show_msg('设置失败');
                                }
                            } else {
                                $this->show_msg('新密码两个不相同');
                            }
                        } else {
                            $this->show_msg('新密码不能空');
                        }                        
                    } else {
                        $this->show_msg('旧密码不正确');
                    }
                }                
            } else {
                $this->show_msg('非法操作');
            }
        } else {
            $this->show_msg('错误操作');
        }
    }

    /**
     * 获取数据
     */
    private function get_data(){
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        if($this->checkIsAdmin()) {
            $where = '';
        } else {
            $where = ' and is_del = 0 and is_admin = 0'; 
        }        
        $filter['user_name'] = isset($_POST['user_name']) ? $_POST['user_name'] : '';
        $filter['email'] = isset($_POST['email']) ? $_POST['email'] : '';
        if(!empty($filter['user_name'])) {
            $where .= ' and instr(user_name, ' . "'{$filter['user_name']}')";
        }
        if(!empty($filter['email'])) {
            $where .= ' and instr(email, ' . "'{$filter['email']}')";
        }
        $sort_by = isset($_REQUEST['sort_by']) ? $_REQUEST['sort_by'] : $this->modelObj->keyFields;
        $sort_order = isset($_REQUEST['sort_order']) ? $_REQUEST['sort_order'] : 'DESC';
        $pageObj = new pageModel('admin_user', $where, $this->page_number, 10, $sort_by, $sort_order);        
        $data = $pageObj->pageData($page);    
        $list = $data['pageData'];
        if($list) {
            foreach ($list as $key => $row) {                
                $data['pageData'][$key]['id'] = $key + 1;
                if($row['is_admin'] == 1) {
                    $data['pageData'][$key]['user_name'] = "<label style='color:#428BCA'>" . $row['user_name'] . '</label>';
                }
                /*判断是否过期*/
                $end_time = $row['end_time'];
                $end_time_format = p_time2str($row['end_time']);
                if($end_time > 0 && p_getTime() > $end_time) {//过期了
                    $this->modelObj->update_user($row['user_id'], 0);
                    $row['is_use'] = 0;
                    $end_time_format = "<label style='color:red' title='{$end_time_format}'>帐号已过期</label>";
                }
                $data['pageData'][$key]['end_time'] = $end_time_format;
                $data['pageData'][$key]['in_time_format'] = publicController::load()->friendlyDate($row['in_time']);
                $last_time_format = empty($row['last_login_time']) ? '-' : publicController::load()->friendlyDate($row['last_login_time']);
                $data['pageData'][$key]['last_time_format'] = $last_time_format;
                $data['pageData'][$key]['is_use'] = $row['is_use'] == 1 ? 'glyphicon-ok' : 'glyphicon-remove';  
            }
        }
        $this->assign('sort_' . $sort_by, $data['sort_img']);
        $this->assign('isadmin', $this->checkIsAdmin());
        $this->assign('data', $data);
    }
    
    public function edit(){
        $this->create_token();
        $user_id = isset($_GET['user_id']) ? $_GET['user_id'] : 0;
        if($user_id > 0) {
            $user_row = AdminUserModel::load()->get_info($user_id);
            if($user_row) {
                $user_row['start_time'] = p_time2str($user_row['start_time']);
                $user_row['end_time'] = p_time2str($user_row['end_time']);
                $this->assign('user_row', $user_row);
                $this->assign('title', '编辑用户');
                $this->assign('act', 'new_create');
                $this->display('user_create');
            } else {
                $this->show_msg('用户不存在');
            }
        } else{
            $this->show_msg('请重新操作');
        }
    }
    /**
     * 新增用户
     */
    public function create() {
        $this->create_token();
        $cookie_str = getCookies($this->cookie_key);
        if($cookie_str) {
            $cookie_str = stripslashes($cookie_str);
            $cookie_arr = json_decode($cookie_str, true);
            $this->assign('cookie', $cookie_arr);
        }        
        $this->assign('title', '新增用户');
        $this->assign('act', 'new_create');
        $this->display('user_create');
    }
    /**
     * 操作用户
     */
    public function new_create() {
        $this->check_token();        
        $cookie_arr = array(
            'user_name' => isset($_POST['user_name']) ? $_POST['user_name'] : '',
            'email' => isset($_POST['email']) ? $_POST['email'] : '',
            'start_time' => isset($_POST['start_time']) ? $_POST['start_time'] : '',
            'end_time' => isset($_POST['end_time']) ? $_POST['end_time'] : '',
        );
        setCookies($this->cookie_key, json_encode($cookie_arr), 600);
        if(!empty($_POST['email'])) {
            $email = $_POST['email'];
            $email_reg = "/[a-z|0-9|A-Z|_]+@[a-z|0-9|A-Z|_]+\.[com|cn|org]/i";
            if(!preg_match($email_reg, $email)) {
                $this->show_msg('您的邮箱格式不对,必须字母或数字或@或下划线');
            }
        }
        $e_user_id = isset($_POST['user_id']) ? $_POST['user_id'] : 0;
        $e_user_name = isset($_POST['user_name']) ? $_POST['user_name'] : '';
        $email_info = AdminUserModel::load()->check_email($e_user_id, $e_user_name, $email);
        if($email_info) {
            $this->show_msg('您的邮箱已被占用');
        }
        /*新增用户操作*/
        if(isset($_POST['user_name']) && $_POST['user_name'] && $_POST['user_pass']) {            
            $user_name = trim($_POST['user_name']);             
            $user_reg = "/[a-z|0-9|A-Z]{2,12}/i";
            if(!preg_match($user_reg, $user_name)) {
                $this->show_msg('用户名必须是字母，数字组合，2位到12位之间');
            }
            $info = AdminUserModel::load()->get_info_byname($user_name);            
            if(empty($info)) {
                $user_pass = $_POST['user_pass'];
                $user_pass_confirm = $_POST['user_pass_confirm'];
                $this->in_user($user_name, 0, $user_pass, $user_pass_confirm, $email);
            } else {
                $this->show_msg($user_name . '用户名已存在');
            }
        }
        /*用户更新操作*/
        elseif(isset($_POST['user_id']) && $_POST['user_id'] > 0) {
            $user_id = intval($_POST['user_id']);
            $user_row = AdminUserModel::load()->get_info($user_id);
            if($user_row) {
                $user_pass = $_POST['user_pass'];
                $user_pass_confirm = $_POST['user_pass_confirm'];
                $this->in_user(null, $user_id, $user_pass, $user_pass_confirm, $email);
            } else {
                $this->show_msg($user_name . '用户名已存在');
            }
        }
        else {
            $this->show_msg('请填写完整信息');
        }
    }
    /**
     * 新增和更新共用
     * @param type $user_name
     * @param type $user_id
     * @param type $user_pass
     * @param type $user_pass_confirm
     * @param type $email
     */
    private function in_user($user_name, $user_id, $user_pass, $user_pass_confirm, $email){
        if(($user_pass && $user_pass_confirm) || $user_id > 0) {                    
            $reg = "/[0-9|a-z|A-Z]{6,12}/i";
            if(!preg_match($reg, $user_pass) && $user_id == 0) {
                $this->show_msg('密码需要在六位到十二位的数字和大小字母');
            }
            if(($user_pass == $user_pass_confirm) || $user_id > 0) {
                $salt = ApiBase::load()->get_unique_id(32, 'salt');
                $md5_pass = pass_encrypt($user_pass, $salt, 'pass_key');                        
                $start_time = !empty($_POST['start_time']) ? p_str2time(trim($_POST['start_time'])) : 0;
                $end_time = !empty($_POST['end_time']) ? p_str2time(trim($_POST['end_time'])) : 0;
                $data = array(
                    'login_ip'  => p_real_ip(),
                    'email'     => $email,
                    'start_time' => $start_time,
                    'end_time'  => $end_time,
                );
                if($user_name && $user_id == 0) {
                    $data['user_name'] = $user_name;
                    $data['in_time'] = time();
                    $data['user_pass'] = $md5_pass;
                    $data['salt'] = $salt;
                    $user_id = AdminUserModel::load()->add_user($data);
                    if($user_id > 0) {
                        $this->admin_log('注册用户user_id:' . $user_id . ',user_name' . $user_name);
                        $this->show_msg('注册成功', 'c=user&m=view');                        
                    } else {
                        $this->show_msg('注册失败');
                    }
                } elseif($user_id > 0) { //更新
                    if($user_pass) {
                        if($user_pass != $user_pass_confirm) {
                            $this->show_msg('两个密码不相同');
                        }
                        $data['user_pass'] = $md5_pass;
                        $data['salt'] = $salt;
                    }
                    $bool = AdminUserModel::load()->update_user_info($user_id, $data);
                    if($bool) {
                        $this->admin_log('更新用户user_id:' . $user_id);
                        $this->show_msg('更新成功', 'c=user&m=view');             
                    } else {
                        $this->show_msg('更新失败');
                    }
                }
            } else {
                $this->show_msg('两个密码不相同');
            }
        } else {
            $this->show_msg('密码为空');
        }
    }    
}

